package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.apis.wemedia.IWemediaClient;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.service.HotArticleService;
import com.heima.common.constants.ArticleConstants;
import com.heima.common.redis.CacheService;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.vos.HotArticleVo;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.wemedia.pojos.WmChannel;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.DateTime;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Transactional
@Slf4j
public class HotArticleServiceImp implements HotArticleService {
    @Autowired
    private ApArticleMapper articleMapper;

    /**
     * 计算热点文章
     */
    @Override
    public void computeHotArticle() {
        //1.查询前5天的文章
        Date dateParam = DateTime.now().minusDays(5).toDate();
        List<ApArticle> articleList = articleMapper.findArticleListByLast5days(dateParam);
        //2.计算文章分值
        List<HotArticleVo> hotArticleVoList = computeHotArticles(articleList);
        //3.为每个频道缓存30条分值较高的文章
        cacaheTagRedis(hotArticleVoList);

    }
    @Autowired
    private IWemediaClient iWemediaClient;
    @Autowired
    private CacheService cacheService;

    /**
     * 为每个频道缓存30条文章
     * @param hotArticleVoList
     */
    private void cacaheTagRedis(List<HotArticleVo> hotArticleVoList) {
        ResponseResult responseResult = iWemediaClient.getChannels();
        if (responseResult.getCode()==200){
            String json = JSON.toJSONString(responseResult.getData());
            List<WmChannel> wmChannels = JSON.parseArray(json, WmChannel.class);
            //检索出每个频道的文章
            if (wmChannels!=null&&wmChannels.size()>0){
                for (WmChannel wmChannel : wmChannels) {
                    List<HotArticleVo> hotArticleVos = hotArticleVoList.stream().filter(x -> x.getChannelId().equals(wmChannel.getId())).collect(Collectors.toList());
                        //给文章进行排序并取30条分值较高的文章存入redis    key:频道id  value:30天分值较高的文章
                    sortAndCache(hotArticleVos, ArticleConstants.HOT_ARTICLE_FIRST_PAGE + wmChannel.getId());
                }
            }
        }
        //设置推荐数据
        sortAndCache(hotArticleVoList, ArticleConstants.HOT_ARTICLE_FIRST_PAGE + ArticleConstants.DEFAULT_TAG);

    }

    /**
     * 排序并且缓存数据
     * @param hotArticleVos
     * @param key
     */
    private void sortAndCache(List<HotArticleVo> hotArticleVos, String key) {
        hotArticleVos = hotArticleVos.stream().sorted(Comparator.comparing(HotArticleVo::getScore).reversed()).collect(Collectors.toList());
        if (hotArticleVos.size()>30){
            hotArticleVos = hotArticleVos.subList(0,30);
    }
        cacheService.set(key, JSON.toJSONString(hotArticleVos));
    }

    /**
     * 计算当前文章分值
     * @param articleList
     * @return
     */
    private List<HotArticleVo> computeHotArticles(List<ApArticle> articleList) {
        List<HotArticleVo> hotArticleVoList=new ArrayList<>();
        if (articleList!=null&&articleList.size()>0){
            for (ApArticle apArticle : articleList) {
                HotArticleVo hot=new HotArticleVo();
                BeanUtils.copyProperties(apArticle,hot);
                Integer score = coumputeScore(apArticle);
                hot.setScore(score);
                hotArticleVoList.add(hot);
            }
        }
        return hotArticleVoList;
    }

    /**
     * 计算文章具体的分值
     * @param apArticle
     * @return
     */
    private Integer coumputeScore(ApArticle apArticle) {
        Integer score = 0;
        if (apArticle.getLikes()!=null){    //点赞 权重 3
            score +=apArticle.getLikes()* ArticleConstants.HOT_ARTICLE_LIKE_WEIGHT;
        }
        if (apArticle.getViews()!=null){    //阅读 权重 1
            score +=apArticle.getViews();
        }
        if (apArticle.getCollection()!=null){    //收藏 权重 8
            score +=apArticle.getCollection()*ArticleConstants.HOT_ARTICLE_COLLECTION_WEIGHT;
        }
        if (apArticle.getComment()!=null){    //评论 权重 5
            score +=apArticle.getComment()*ArticleConstants.HOT_ARTICLE_COMMENT_WEIGHT;
        }
        return score;
    }
}
